package cn.tianyigps.tianyigpselectricfence.handler;

import cn.tianyigps.tianyigpselectricfence.dao.ElectricFenceDao;
import cn.tianyigps.tianyigpselectricfence.dto.GeoFenccRequestDto;
import cn.tianyigps.tianyigpskafka.task.manger.NewTaskManager;
import cn.tianyigps.tianyigpspublic.param.bo.Task;
import cn.tianyigps.tianyigpspublic.bean.GeoFence;
import cn.tianyigps.tianyigpspublic.param.constant.EquipmentReceiveConstant;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author: WEI.YUAN
 * @Descirption:处理电子围栏
 * @Date: 2019/4/11_11:21
 */
@Component
@Slf4j
public class ElectricFenceHandler {

    //围栏组
    private final static String group = "group";

    private static ObjectMapper OM = new ObjectMapper();

    @Autowired
    ElectricFenceDao electricFenceDao;

    @Autowired
    NewTaskManager newTaskManager;

    public void checkElectricFence(Task task) {
        Map<String, String> map = task.getParams();

        //获取task中的经纬度参数
        GeoFenccRequestDto geoFenccRequestDto = new GeoFenccRequestDto();
        geoFenccRequestDto.setEquipmentId(map.get(EquipmentReceiveConstant.DeviceCode).toString());
        try {

            geoFenccRequestDto.setLongitude(Double.valueOf(EquipmentReceiveConstant.Longitude));
            geoFenccRequestDto.setLatitude(Double.valueOf(EquipmentReceiveConstant.Latitude));


            if (map.containsKey(group) && !StringUtils.isEmpty(map.get(group))) {
                geoFenccRequestDto.setGroup(String.valueOf(map.get(group)));
            }
            //设备所在位置的围栏集合
            List<GeoFence> geoFences = electricFenceDao.getFenceByLocation(geoFenccRequestDto);
            //调用任务分发接口
            this.handTask(geoFences, task);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 调用任务分发接口
     *
     * @param geoFences
     * @param task
     */
    public void handTask(List<GeoFence> geoFences, Task task) {
        //得到围栏id集合
        List<String> fenceIdList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(geoFences)) {
            geoFences.parallelStream()
                    .forEach(e -> fenceIdList.add(e.getId()));
        }

        Task nextTask = task.getNext();
        Map<String, String> nextMap = nextTask.getParams();

        if (!CollectionUtils.isEmpty(geoFences)) {
            nextMap.put("fenIdList", fenceIdList.toString());
        }
        nextTask.setParams(nextMap);
        try {
            newTaskManager.distributeTask(nextTask.getType(), OM.writeValueAsString(nextTask));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("task序列化异常:{}", e);
        }

    }

}
